const canvas = document.querySelector("#canvas");
const context = canvas.getContext("2d");
const ERASER_SIZE = 20;
const point = { x: 0, y: 0 };
let lastX, lastY,dragging = false;

function windowToCanvas(x, y) {
    let bbox = canvas.getBoundingClientRect();
    return {
        x: x - bbox.left * (canvas.width / bbox.width),
        y: y - bbox.top * (canvas.height / bbox.height)
    };
}

function drawBackground() {
    context.save();
    context.fillStyle = "#000";
    context.fillRect(0, 0, canvas.width, canvas.height);
    context.restore();
}

function drawEraser(loc) {
    context.save();
    context.strokeStyle = "rgba(0,0,0,0)";
    context.lineWidth     = 1;
    context.shadowColor   = 'blue';
    context.shadowOffsetX = -5;
    context.shadowOffsetY = -5;
    context.shadowBlur    = 20;

    context.beginPath()
    context.rect(
        loc.x - ERASER_SIZE / 2,
        loc.y - ERASER_SIZE / 2,
        ERASER_SIZE,
        ERASER_SIZE
    );
    context.clip();

    context.stroke();
    context.restore();
}

function setErasePathForEraser() {
    context.beginPath();

    context.rect(
        lastX - ERASER_SIZE / 2,
        lastY - ERASER_SIZE / 2,
        ERASER_SIZE,
        ERASER_SIZE
    );
    context.clip();
}

function eraseLast() {
    context.save();

    setErasePathForEraser();
    drawBackground();

    context.restore();
}

canvas.onmousedown = e => {
    const { x, y } = windowToCanvas(e.clientX, e.clientY);
    lastX = point.x = x;
    lastY = point.y = y;
    dragging = true;
};

canvas.onmousemove = e => {
    if (dragging) {
        const { x, y } = windowToCanvas(e.clientX, e.clientY);
        eraseLast();
        drawEraser({ x, y });
        lastX = x;
        lastY = y;
    }
};

canvas.onmouseup = function(e) {
    eraseLast();

    dragging = false;
};

drawBackground();

context.beginPath();
context.fillStyle = "#fff";
context.arc(canvas.width / 2, canvas.height / 2, 100, 0, Math.PI * 2, false);
context.fill();
